//
//  XGAdvertisementManager.m
//  BSBuDeJie
//
//  Created by monkey on 2018/12/11.
//  Copyright © 2018 itcast. All rights reserved.
//

#import <SDWebImage/SDWebImageDownloader.h>

#import "XGAdvertisementManager.h"
#import "XGDataManager.h"

#import "XGAdvertisementModel.h"

/// 广告图片下载地址在沙盒中的key
static NSString *const kDownloadImageURLKey = @"kDownloadImageURLKey";
/// 广告图片跳转网页在沙盒中的key
static NSString *const kAdvertisementWebURLKey = @"kAdvertisementWebURLKey";

@implementation XGAdvertisementManager
{
    /// 广告模型数据
    XGAdvertisementModel *_advertisementModel;
    /// 图片保存路径
    NSString *_filePath;
    /// 广告图片
    UIImage *_image;
    /// 广告图片跳转网页
    NSString *_webUrl;
}

#pragma mark - 单例

+ (instancetype)sharedManager
{
    static id instance;
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        instance = [[self alloc] init];
    });
    
    return instance;
}

- (instancetype)init
{
    if (self = [super init]) {
        _filePath = [NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES).lastObject stringByAppendingPathComponent:@"Advertisement.png"];
        _image = [UIImage imageWithData:[NSData dataWithContentsOfFile:_filePath]];
        _webUrl = [[NSUserDefaults standardUserDefaults] objectForKey:kAdvertisementWebURLKey];
    }
    
    return self;
}

#pragma mark - 开放方法

- (BOOL)isNeedShowAdvertisement
{
    if (![[NSFileManager defaultManager] fileExistsAtPath:_filePath]) {
        [self loadData];
        return NO;
    } else {
        [self loadData];
        return YES;
    }
}

- (UIImage *)advertisementImage
{
    return _image;
}

- (NSURL *)webUrl
{
    if (_webUrl != nil) {
        return [NSURL URLWithString:_webUrl];
    } else {
        return nil;
    }
}

#pragma mark - 私有方法

// 加载广告数据
- (void)loadData
{
    [XGDataManager loadAdvertisement:^(XGAdvertisementModel * _Nullable advertisementModel, NSError * _Nullable error) {
        if (error) {
            DEBUG_Log(@"广告数据请求失败!");
            return;
        }
        
        // 保存数据模型
        self->_advertisementModel = advertisementModel;
        // 如果当前图片已经下载过了 无需下载 否则进行下载
        if ([[[NSUserDefaults standardUserDefaults] stringForKey:kDownloadImageURLKey] isEqualToString:advertisementModel.url]) {
            return;
        } else {
            [[NSUserDefaults standardUserDefaults] setObject:advertisementModel.url forKey:kDownloadImageURLKey];
            [[NSUserDefaults standardUserDefaults] setObject:advertisementModel.webUrl forKey:kAdvertisementWebURLKey];
            [[NSUserDefaults standardUserDefaults] synchronize];
            // 下载广告图片
            [self downloadImage];
        }
    }];
}

// 下载广告图片
- (void)downloadImage
{
    [[SDWebImageDownloader  sharedDownloader] downloadImageWithURL:[NSURL URLWithString:_advertisementModel.url] options:0 progress:nil completed:^(UIImage * _Nullable image, NSData * _Nullable data, NSError * _Nullable error, BOOL finished) {
        if (error) {
            DEBUG_Log(@"广告图片下载失败!");
            return;
        }
        
        // 保存广告图片到沙盒中 如果已经存在旧图片 先删除旧图片 然后保存新图片
        if ([[NSFileManager defaultManager] fileExistsAtPath:self->_filePath]) {
            [[NSFileManager defaultManager] removeItemAtPath:self->_filePath error:nil];
        }
        
        [data writeToFile:self->_filePath atomically:YES];
    }];
}

@end
